//! # 配置存储抽象层
//!
//! 提供配置存储的统一抽象接口，实现存储层的高内聚低耦合设计。
//! 支持多种存储后端（Git、数据库、文件系统等）的插件化扩展。

use std::sync::Arc;
use async_trait::async_trait;

use crate::core::*;

/// 配置存储后端trait
/// 
/// 继承核心接口的ConfigurationStorage，提供统一的存储抽象
#[async_trait]
pub trait ConfigStorageBackend: ConfigurationStorage + Send + Sync {
    /// 获取存储后端名称
    fn backend_name(&self) -> &str;
    
    /// 获取存储后端版本
    fn backend_version(&self) -> &str;
    
    /// 获取存储后端配置信息
    fn backend_config(&self) -> serde_json::Value;
}

/// Git存储后端实现
/// 
/// 实现ConfigStorageBackend trait，提供Git存储功能
pub struct GitStorageBackend {
    /// 核心Git存储实现
    inner: super::git::GitStorage,
}

impl GitStorageBackend {
    /// 创建新的Git存储后端
    pub fn new(config: &super::ConfigurationServerConfig) -> super::ServerResult<Self> {
        let inner = super::git::GitStorage::new(config)?;
        Ok(Self { inner })
    }
}

#[async_trait]
impl ConfigurationStorage for GitStorageBackend {
    async fn load(&self, environment: &ConfigEnvironment) -> ConfigurationResult<ConfigurationData> {
        // 转换环境信息
        let env = super::ConfigEnvironment {
            application: environment.application.clone(),
            profile: environment.profile.clone(),
            label: environment.label.clone(),
            version: None,
            state: None,
        };
        
        // 调用内部实现
        match self.inner.load_config(&env).await {
            Ok(response) => {
                let data = ConfigurationData {
                    environment: environment.clone(),
                    config: response.config,
                    version: response.version.unwrap_or_else(|| "unknown".to_string()),
                    last_modified: std::time::SystemTime::now(),
                    source: "git".to_string(),
                    properties: response.property_sources.into_iter().map(|ps| {
                        (ps.name, serde_json::Value::String(ps.source.unwrap_or_default()))
                    }).collect(),
                };
                Ok(data)
            }
            Err(e) => Err(Box::new(e)),
        }
    }
    
    async fn save(&self, data: &ConfigurationData, user: &str) -> ConfigurationResult<String> {
        // 转换环境信息
        let env = super::ConfigEnvironment {
            application: data.environment.application.clone(),
            profile: data.environment.profile.clone(),
            label: data.environment.label.clone(),
            version: None,
            state: None,
        };
        
        // 调用内部实现
        match self.inner.save_config(&env, &data.config, user).await {
            Ok(version) => Ok(version),
            Err(e) => Err(Box::new(e)),
        }
    }
    
    async fn delete(&self, environment: &ConfigEnvironment, user: &str) -> ConfigurationResult<()> {
        // 转换环境信息
        let env = super::ConfigEnvironment {
            application: environment.application.clone(),
            profile: environment.profile.clone(),
            label: environment.label.clone(),
            version: None,
            state: None,
        };
        
        // 调用内部实现
        match self.inner.delete_config(&env, user).await {
            Ok(()) => Ok(()),
            Err(e) => Err(Box::new(e)),
        }
    }
    
    async fn get_history(&self, environment: &ConfigEnvironment) -> ConfigurationResult<Vec<ConfigurationChange>> {
        // 转换环境信息
        let env = super::ConfigEnvironment {
            application: environment.application.clone(),
            profile: environment.profile.clone(),
            label: environment.label.clone(),
            version: None,
            state: None,
        };
        
        // 调用内部实现
        match self.inner.get_history(&env).await {
            Ok(changes) => {
                let core_changes = changes.into_iter().map(|change| {
                    ConfigurationChange {
                        id: change.id,
                        environment: environment.clone(),
                        operation: match change.operation {
                            super::ConfigOperation::Create => ChangeOperation::Create,
                            super::ConfigOperation::Update => ChangeOperation::Update,
                            super::ConfigOperation::Delete => ChangeOperation::Delete,
                            super::ConfigOperation::Rollback => ChangeOperation::Rollback,
                        },
                        user: change.user,
                        timestamp: change.timestamp,
                        description: change.description,
                        old_config: change.old_config,
                        new_config: change.new_config,
                        details: change.details.into_iter().map(|(k, v)| {
                            (k, ChangeDetail {
                                path: v.path,
                                old_value: v.old_value,
                                new_value: v.new_value,
                            })
                        }).collect(),
                    }
                }).collect();
                Ok(core_changes)
            }
            Err(e) => Err(Box::new(e)),
        }
    }
    
    async fn rollback(&self, environment: &ConfigEnvironment, version: &str, user: &str) -> ConfigurationResult<()> {
        // 转换环境信息
        let env = super::ConfigEnvironment {
            application: environment.application.clone(),
            profile: environment.profile.clone(),
            label: environment.label.clone(),
            version: None,
            state: None,
        };
        
        // 调用内部实现
        match self.inner.rollback_config(&env, version, user).await {
            Ok(()) => Ok(()),
            Err(e) => Err(Box::new(e)),
        }
    }
    
    async fn initialize(&self) -> ConfigurationResult<()> {
        match self.inner.initialize().await {
            Ok(()) => Ok(()),
            Err(e) => Err(Box::new(e)),
        }
    }
    
    async fn health_check(&self) -> ConfigurationResult<bool> {
        match self.inner.health_check().await {
            Ok(status) => Ok(matches!(status, super::HealthStatus::Healthy)),
            Err(e) => Err(Box::new(e)),
        }
    }
}

impl ConfigStorageBackend for GitStorageBackend {
    fn backend_name(&self) -> &str {
        "Git"
    }
    
    fn backend_version(&self) -> &str {
        "1.0.0"
    }
    
    fn backend_config(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "git",
            "path": self.inner.repo_path.display().to_string(),
            "remote_url": self.inner.remote_url,
        })
    }
}